<?php
// 应用公共文件
/**
 * getOnly
 * @des 生成唯一编号
 * @return string
 * @author
 */
function getOnly()
{
    $yCode   = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99)) . "ZS";
    return $orderSn;
}

function passport_encrypt($txt, $key = 'ours') {
    srand((double)microtime() * 1000000);
    $encrypt_key = md5(rand(0, 32000));
    $ctr = 0;
    $tmp = '';
    for($i = 0;$i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
    }
    return urlencode(base64_encode(passport_key($tmp, $key)));
}

function passport_decrypt($txt, $key = 'ours') {
    $txt = passport_key(base64_decode(urldecode($txt)), $key);
    $tmp = '';
    for($i = 0;$i < strlen($txt); $i++) {
        $md5 = $txt[$i];
        $tmp .= $txt[++$i] ^ $md5;
    }
    return $tmp;
}

function passport_key($txt, $encrypt_key) {
    $encrypt_key = md5($encrypt_key);
    $ctr = 0;
    $tmp = '';
    for($i = 0; $i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
    }
    return $tmp;
}

/**
 * getStr
 * @des 随机字符串
 * @param $len
 * @return string
 * @author
 */
function getStr($len)
{
    $chars_array = array(
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z",
    );
    $charsLen    = count($chars_array) - 1;

    $outputstr = "";
    for ( $i = 0; $i < $len; $i++ ) {
        $outputstr .= $chars_array[mt_rand(0, $charsLen)];
    }
    return $outputstr;
}

/**
 * getStr
 * @des 参数解密
 * @param string
 * @return string
 * @author VN
 */
function getv($name)
{
    $param = request()->param($name);
    return strip_tags(base64_decode($param));
}

/**
 * priceCalculate
 * @des 高精度价格计算
 * @param  float  $n1 数1
 * @param  string $symbol
 * @param  float  $n2
 * @param string  $scale
 * @return string
 * @author
 */
function priceCalculate($n1, $symbol, $n2, $scale = '2')
{
    $res = '';
    switch ($symbol) {
        case '+'://加法
            $res = bcadd($n1, $n2, $scale);
            break;
        case '-'://减法
            $res = bcsub($n1, $n2, $scale);
            break;
        case '*'://乘法
            $res = bcmul($n1, $n2, $scale);
            break;
        case '/'://除法
            $res = bcdiv($n1, $n2, $scale);
            break;
        case '%'://求余、取模
            $res = bcmod($n1, $n2);
            break;
        default:
            $res = '';
            break;
    }
    return (float)$res;
}


/* @des 接口返回json
 * @param bool status msg data
 * @return json
 * @author  vn
 */

function returnJson($bool,$code,$msg,$data=null){
    $result=[];
    $result['status'] = $bool;
    $result['code'] = $code;
    $result['msg'] = $msg;
    $data === null ?: $result['data'] = $data;
    echo json_encode($result);
    \think\facade\Session::save();
    exit;
}

function get_real_ip()
{
    $ip = FALSE;
    //客户端IP 或 NONE
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }

//    //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
//    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//        $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
//        if ($ip) {
//            array_unshift($ips, $ip);
//            $ip = FALSE;
//        }
//        for ( $i = 0; $i < count($ips); $i++ ) {
//            if (!preg_match("^(10│172.16│192.168).", $ips[$i])) {
//                $ip = $ips[$i];
//                break;
//            }
//        }
//    }
    //客户端IP 或 (最后一个)代理服务器 IP
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);

}

/**
 * getIPLocation
 * @des 查询ip所属地区
 * @param string $queryIP
 * @return null
 */
function getIPLocation($queryIP = '')
{
    if (filter_var($queryIP, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
        $url = "http://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=" . $queryIP . "&co=&resource_id=6006";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_ENCODING, 'gb2312');
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回
        $result = curl_exec($ch);
        $result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换
        $ip_res = json_decode($result, true);
        if (!$ip_res['status']) {
            return $ip_res['data']['0']['location'];
        }
    }
    return null;
}

/**
 * 把ip转换为整数
 * @return int
 */
function ipToLong($ip)
{
    $ip = ($ip == "::1") ? "127.0.0.1" : $ip;
    return ip2long($ip);
}

/**
 * 把返回的数据集转换成Tree
 * @param array  $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0, $isTree = True)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ( $list as $key => $data ) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ( $list as $key => $data ) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            switch ($isTree) {
                case false;
                    if ($root == $parentId) {
                        $tree[] =& $list[$key];
                    }
                    break;
                default:
                    if ($root == $parentId) {
                        $tree[] =& $list[$key];
                    } else {
                        if (isset($refer[$parentId])) {
                            $parent           =& $refer[$parentId];
                            $parent[$child][] =& $list[$key];
                        }
                    }
            }

        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array  $tree 原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list 过渡用的中间数组，
 * @return array        返回排过序的列表数组
 */
function tree_to_list($tree, $child = 'child', $order = 'id', &$list = array())
{
    if (is_array($tree)) {
        $refer = array();
        foreach ( $tree as $key => $value ) {
            $reffer = $value;
            if (isset($reffer[$child])) {
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby = 'asc');
    }
    return $list;
}



/**
 * 打印数据
 * author:
 * @param $data
 */
function p($data)
{
    echo '<pre>';
    print_r($data);
//    echo '</pre>';
    die;

}

function dp($data)
{
    echo '<pre>';
    var_dump($data);
    echo '</pre>';
    die;
}


/**
 * 判断参数是否为空
 * author:
 * @param $data
 */
function param_empty($data)
{
    //非数组参数转数组
    if (!is_array($data)){
        $arr[] = $data;
    }else{
        $arr = $data;
    }
    foreach ($arr as $v){
        if ($v === '' || empty($v)){
            returnJson(false,1002,'参数不能为空');
        }
    }
}
/**
 * 判断验证码是否正确
 * author: VN
 * @param $code
 */
function check_code($code)
{
    param_empty($code);
    if( !captcha_check($code)){
        returnJson(false,2000,'验证码不正确或已失效~');
    }
}

/**
 * 判断是否登录
 * author: VN
 * @param $code
 */
function isLogin()
{
    $id = session('uid');
    if (!$id){
        //请先登录
        returnJson(false,3000,'请先登录~QAQ!!');
    }
    return $id;
}
/**
 * 今日时间戳
 * author: VN
 * @param $time
 */
function today_time($type = 'start')
{
    if($type == 'start'){
        return mktime(0,0,0,date('m'),date('d'),date('Y'));     // 今日开始时间
    }
    if ($type == 'end'){
        return mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;  // 今日结束时间
    }
}

/**
 * 文件删除的方法
 * author: VN
 * @param $time
 */
function fileDel($fileName)
{
    if ($fileName){
        //文件名必须是  ./  开头
        $name = '.'.$fileName;
    }
    //检测文件是否存在
    if (file_exists($name)){
        $result = unlink($name);
        return $result;     //成功返 true   失败返 false
    }
    return 'null';  //文件不存在
}

/**
 * 判断是否是 GET 请求
 * author: VN
 * @param $time
 */
function is_get()
{
    if( $_SERVER['REQUEST_METHOD'] === 'GET'){
        return true;
    }else{
        return false;
    }
}
